//
//  VideoSetViewController.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/2/27.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

class VideoSetViewController: BaseTRTCViewController {
    
    var list:[String] = ["当前摄像头","分辨率","视频帧率","视频码率","横屏竖屏","其他设置"]//["当前摄像头","其他"]//
    var uCusViews:[CuSetView] = []
    var uObtns:[NSButton] = []
    
    override func loadView() {
        let view = NSView.init(frame: NSMakeRect(0, 0, kSet_BasicWidth, 600))
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.white.cgColor
        self.view = view
    }
    
    lazy var config: TRTCVideoEncParam = {
        let config = TRTCVideoEncParam()
        return config
    }()
    
    lazy var qosParam: TRTCNetworkQosParam = {
        let param = TRTCNetworkQosParam()
        return param
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupUI()
        self.loadData()
    }
    func loadData() {
        TRTCCloud.sharedInstance()?.startCameraDeviceTest(in: self.videoView)
        
        let param = Td.sh().videoParam
        self.videoResolutionBtn.title = param.videoResolution
        self.fpsBtn.title = String(param.videoFps)+"fps"
        self.slide.currentValue = param.videoBitrate
        self.modeBtn.title = param.resMode==0 ? "横屏模式":"竖屏模式"
        
    }
    
    func setupUI() {
        self.view.layer?.backgroundColor = color_gray(233).cgColor
        
        self.view.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.width.height.centerX.equalToSuperview()
        }
        clipView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.width.height.centerX.equalToSuperview()
        }
        
        containt.snp.makeConstraints { (make) in
            make.width.top.centerX.equalToSuperview()
            make.height.equalTo(300+380)
        }
        
        containt.addSubview(bgVideoView)
        bgVideoView.snp.makeConstraints { (make) in
            make.width.equalToSuperview().offset(-40)
            make.top.equalTo(30)
            make.height.equalTo(300)
            make.centerX.equalToSuperview()
        }
        
        bgVideoView.addSubview(videoView)
        videoView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        containt.addSubview(setView)
        setView.snp.makeConstraints { (make) in
            make.width.equalToSuperview().offset(-40)
            make.top.equalTo(bgVideoView.snp.bottom).offset(20)
            make.bottom.equalToSuperview()
            make.centerX.equalToSuperview()
        }
        
        //初始化子类
        self.uCusViews = self.initCusViews(inView: self.setView)
    }
    
    lazy var scrollView: NSScrollView = {
        let view = NSScrollView()
        view.automaticallyAdjustsContentInsets = true
        view.hasVerticalScroller = true
        view.backgroundColor = NSColor.clear
        view.contentView = self.clipView
        return view
    }()
    lazy var clipView: NSClipView = {
        let clipView = NSClipView.init(frame: CGRect.zero)
        clipView.documentView = self.containt;
        clipView.documentView?.enclosingScrollView?.scrollerInsets = NSEdgeInsetsMake(0, 0, 0, 0)
        return clipView
    }()
    
    lazy var containt: NSView = {
        let view = NSView()
        return view
    }()
    
    
    lazy var setView: NSView = {
        let view = NSView()
        return view
    }()
    
    lazy var bgVideoView: NSView = {
        let view = NSView.init()
        view.wantsLayer = true
        view.layer?.backgroundColor = color_gray(0).cgColor
        view.layer?.cornerRadius = 20
        view.layer?.masksToBounds = true
        return view
    }()
    
    lazy var videoView: NSImageView = {
        let imageV = NSImageView.init(image: NSImage.image(name:"icon_camera_preview")!)
        imageV.wantsLayer = true
        imageV.layer?.backgroundColor = color_gray(0).cgColor
        imageV.layer?.cornerRadius = 20
        imageV.layer?.masksToBounds = true
        return imageV
    }()
    
    func getCameraDevicesList() -> [TRTCMediaDeviceInfo] {
        let list = TRTCCloud.sharedInstance()?.getCameraDevicesList()
        return list ?? []
    }
    
    lazy var deviceBtn: NSPopUpButton = {
        let list = self.getCameraDevicesList()
        let deviceName = list.map { (info) -> String in
            return info.deviceName ?? "未知设备"
        }
        let current = TRTCCloud.sharedInstance()?.getCurrentCameraDevice()?.deviceName
        let btn = NSPopUpButton.init(title: current ?? "未知设备", target: self, action: #selector(deviceBtnAction(senber:)))
        btn.addItems(withTitles: deviceName)
        return btn
    }()
    
    lazy var videoResolutionBtn: NSPopUpButton = {
        let btn = NSPopUpButton.init(title: "320x180", target: self, action: #selector(videoResolutionAction(senber:)))
        btn.addItems(withTitles: ["160x160","320x180","320x240","320x180","480x480","640x360","640x360","640x480","960x540","1280x720"])
        return btn
    }()
    
    lazy var fpsBtn: NSPopUpButton = {
        let btn = NSPopUpButton.init(title: "25fps", target: self, action: #selector(fpsBtnAction(senber:)))
        btn.addItems(withTitles: ["15fps","20fps","25fps"])
        return btn
    }()
    
    lazy var slide: VideoSlide = {
        let view = VideoSlide.init(value: 1000, minValue: 500, maxValue: 2000) { (value) in
            self.slideAction(value:value)
        }
        return view
    }()
    
    
    lazy var modeBtn: NSPopUpButton = {
        let btn = NSPopUpButton.init(title: "横屏模式", target: self, action: #selector(modeBtnAction(senber:)))
        btn.addItems(withTitles: ["横屏模式","竖屏模式"])
        return btn
    }()
    
    lazy var otherButtomView: NSView = {
        let view = NSView.init(frame: NSRect.zero)
        self.uObtns = self.initOtherButtom(inView: view)
        return view
    }()
    
    func initOtherButtom(inView:NSView) -> [NSButton] {
        var uBtns:[NSButton] = []
        let btnTitles:[String] = ["开启本地视频镜像","开启填充模式","开启美颜"]
        for (inx,val) in btnTitles.enumerated() {
            let btn = NSButton.init(title: val, target: self, action: #selector(otherButtomAction(senber:)))
            btn.tag = 100+inx
            btn.setButtonType(NSButton.ButtonType.switch)
            btn.state = .on
            inView.addSubview(btn)
            uBtns.append(btn)
            btn.snp.makeConstraints { (make) in
                make.width.equalToSuperview()
                make.left.equalToSuperview()
                make.top.equalTo(inx*32)
                make.height.equalTo(24)
            }
        }
        return uBtns
    }
    
    func initCusViews(inView:NSView) -> [CuSetView] {
        
        var uCusViews:[CuSetView] = []
        for (inx,val) in self.list.enumerated() {
            var cusV:NSView?
            var cusSize:CGSize = CGSize.init(width: 220, height: 26)
            switch inx {
            case 0:
                cusV = self.deviceBtn
            case 1:
                cusV = self.videoResolutionBtn
            case 2:
                cusV = self.fpsBtn
            case 3:
                cusV = self.slide
            case 4:
                cusV = self.modeBtn
            case 5:
                cusV = self.otherButtomView
                cusSize = CGSize.init(width: cusSize.width, height: 32*3)
            default:
                break
            }
            
            let cusView = CuSetView.init(text: val+" ", cusView: cusV, cusSize: cusSize)
            cusView.titleWidth = 220
            inView.addSubview(cusView)
            uCusViews.append(cusView)
            cusView.snp.makeConstraints { (make) in
                make.width.equalTo(cusSize.width+cusView.titleWidth+30)
                make.height.equalTo(cusSize.height)
                make.centerX.equalToSuperview().offset(-80)
                if inx == 0 {
                    make.top.equalTo(0)
                }else {
                    make.top.equalTo(uCusViews[inx-1].snp.bottom).offset(15)
                }
                
            }
        }
        return uCusViews
    }
    
    @objc func deviceBtnAction(senber:NSPopUpButton) {
        senber.title = senber.selectedItem!.title
    }
    
    @objc func videoResolutionAction(senber:NSPopUpButton) {
        senber.title = senber.selectedItem!.title
        self.config.videoResolution = TXLiteManager._resolutionFromIndex(resolutionIndex: senber.indexOfSelectedItem)
        TRTCCloud.sharedInstance()?.setVideoEncoderParam(self.config)
        Td.sh().videoParam.videoResolution = senber.title
    }
    
    @objc func fpsBtnAction(senber:NSPopUpButton) {
        senber.title = senber.selectedItem!.title
        let int = 15+senber.indexOfSelectedItem*5
        self.config.videoFps = Int32(int)
        TRTCCloud.sharedInstance()?.setVideoEncoderParam(self.config)
        Td.sh().videoParam.videoFps = int
    }
    
    @objc func modeBtnAction(senber:NSPopUpButton) {
        senber.title = senber.selectedItem!.title
        self.config.resMode = senber.indexOfSelectedItem==0 ? .landscape:.portrait
        TRTCCloud.sharedInstance()?.setVideoEncoderParam(self.config)
        Td.sh().videoParam.resMode = senber.indexOfSelectedItem
    }
    
    @objc func otherButtomAction(senber:NSPopUpButton) {
        switch senber.tag {
        case 100:
            TRTCCloud.sharedInstance()?.setLocalViewMirror((senber.state == .off))
        case 101:
            let mode = (senber.state == .on) ? TRTCVideoFillMode.fit:TRTCVideoFillMode.fill
            TRTCCloud.sharedInstance()?.setLocalViewFillMode(mode)
        case 102:
            TXLiteManager.shared().setBeauty(isOn: (senber.state == .on))
        default:
            break
        }
    }
    
    @objc func slideAction(value:Int) {
        self.config.videoBitrate = Int32(value)
        TRTCCloud.sharedInstance()?.setVideoEncoderParam(self.config)
        Td.sh().videoParam.videoBitrate = Int(value)
    }
}


